package com.eapi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eapi.eapicommom.model.entity.User;
import com.eapi.project.common.BaseResponse;
import com.eapi.project.common.ErrorCode;
import com.eapi.project.common.ResultUtils;
import com.eapi.project.exception.BusinessException;
import com.eapi.project.mapper.ArticlelikerecordMapper;
import com.eapi.project.model.dto.article.ArticleLikeRequest;
import com.eapi.project.model.entity.Article;
import com.eapi.project.model.entity.Articlelikerecord;

import com.eapi.project.service.ArticleService;
import com.eapi.project.service.ArticlelikerecordService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author lenovo
* @description 针对表【articlelikerecord(点赞记录表)】的数据库操作Service实现
* @createDate 2024-06-20 21:39:16
*/
@Service
public class ArticlelikerecordServiceImpl extends ServiceImpl<ArticlelikerecordMapper, Articlelikerecord>
    implements ArticlelikerecordService {

    @Resource
    private ArticleService articleService;

    @Override
    public BaseResponse<String> likeArticle(ArticleLikeRequest articleLikeRequest, User loginUser) {
        //判断请求是否合法
        Long articleId = articleLikeRequest.getArticleId();
        if(articleLikeRequest == null || articleId <=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);//抛出参数异常
        }
        // 获取原文章
        Article oldArticle = articleService.getById(articleId);
        // 判断该用户是否点过赞
        Long userId = loginUser.getId();
        LambdaQueryWrapper<Articlelikerecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Articlelikerecord::getUserId,userId);
        queryWrapper.eq(Articlelikerecord::getArticleId,articleId);
        Articlelikerecord articlelikerecord = getOne(queryWrapper);
        if(articlelikerecord != null){
            // throw new BusinessException(ErrorCode.PARAMS_ERROR,"请勿重复点赞");
            // 取消点赞
            // 删除数据库中的点赞记录
            removeById(articlelikerecord.getId());
            // 将article中的点赞数减一
            oldArticle.setLikes(oldArticle.getLikes() - 1);
            articleService.updateById(oldArticle);
            return ResultUtils.success("点赞已取消");
        }
        else{
            // 执行点赞
            Articlelikerecord newlikerecord = new Articlelikerecord();
            newlikerecord.setArticleId(articleId);
            newlikerecord.setUserId(userId);
            save(newlikerecord);
            // 更新点赞数
            oldArticle.setLikes(oldArticle.getLikes() + 1);
            articleService.updateById(oldArticle);
            return ResultUtils.success("点赞成功");
        }
    }
}




